import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse
} from '@angular/common/http';

import { Router } from '@angular/router';
import { Observable, tap, finalize } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

  constructor(private message: NzMessageService, private router: Router) { }

  // 拦截器
  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    const token = '123456';

    const authReq = request.clone({
      url: request.url,
      headers: request.headers.set('Authorization', token)
    });

    // return next.handle(authReq);
    // 应用响应拦截器
    return next.handle(authReq).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          // success
        }
      }, error => {
        switch (error.status) {
          case 401:
            this.router.navigateByUrl(`/login`);
            break;
        }
        this.message.create('error', `${error.status} : ${error.statusText}`, { nzDuration: 5000 });
      }),
      finalize(() => {
        // 请求完成
        // console.log('complete')
      })
    )
  }
}
